import React, { useState, useEffect, useRef } from "react";
import HomeHead from "../components/HomeHead";
import _ from '../assets/utils'
import { Swiper, Image, Divider, DotLoading } from "antd-mobile";
import { Link } from "react-router-dom";
import './less/Home.less'
import api from '../api'
import NewsItem from '../components/NewsItem'
import SkeletonAgain from '../components/SkeletonAgain'
import { withError } from "antd/es/modal/confirm";

const Home = function () {

    //创建所需状态
    let [today, setToday] = useState(_.formatTime(null, '{0}{1}{2}'));
    let [bannerData, setBannerData] = useState([]); 
    let [newsList, setNewsList] = useState([]);
    let loadMore = useRef();
    // 第一次渲染完毕，向服务器发送请求
    useEffect(() => {
        (async () => {
            try {
                let { date, stories, top_stories } = await api.queryNewsLastest();
                setToday(date);
                setBannerData(top_stories);
                newsList.push({
                    date,
                    stories
                })
                setNewsList([...newsList]);
            } catch (err) {
                console.log(err);
            }
        })();
    }, [])
    //第一次渲染完毕，设置监听器，实现触底加载
    useEffect(() => {
        let ob = new IntersectionObserver(async changes => {
            let { isIntersecting } = changes[0];
            if (isIntersecting) {
                //触底完成
                try {
                    let time = newsList[newsList.length - 1]['date'];
                    let res = await api.queryNewsBefore(time);
                    newsList.push(res);
                    setNewsList([...newsList]);
                } catch (err) {
                    console.log(err);
                }
            }

        })
        ob.observe(loadMore.current)
        let loadMoreBox = loadMore.current
        //组件销毁时移除监听
        return () => {
            ob.unobserve(loadMoreBox)
            ob = null
        }

    }, [])
    return <div className="home-box">
        {/* 头部 */}
        <HomeHead today={today} />
        {/* 轮播图 */}
        <div className="swiper-box">
            {bannerData.length > 0 ? <Swiper autoplay={false} loop={true}>
                {bannerData.map((item) => {
                    let { id, image, title, hint } = item;
                    return <Swiper.Item key={id}>
                        <Link to={`/detail/${id}`}>
                            <Image src={image} lazy />
                            <div className="desc">
                                <h3 className="title">{title}</h3>
                                <p className="author">{hint}</p>
                            </div>
                        </Link>
                    </Swiper.Item>
                })}
            </Swiper> : null}
        </div>

        {/* 新闻列表 */}
        {newsList.length === 0 ? <SkeletonAgain /> :
            <>
                {
                    newsList.map((item, index) => {
                        let { date, stories } = item;
                        return <div className="news-box" key={date}>
                            {
                                index === 0 ? null : <Divider contentPosition="left">
                                    {_.formatTime(date, "{1}年{2}日")}
                                </Divider>
                            }
                            <div className="list">
                                {stories.map((news) => {
                                    return <NewsItem key={news.id} info={news} />
                                })}
                            </div>
                        </div>
                    })
                }
            </>
        }
        {/* 加载更多 */}
        <div className="loadmore" ref={loadMore} style={{
            display: newsList.length === 0 ? "none" : "block"
        }}>
            加载更多
            <DotLoading />
        </div>
    </div >
}

export default Home;